﻿using System.Linq;
using System.Web.Mvc;
using System.Collections.Generic;
using System;
using ASPNETMVCApplication.Code.Filters;
using ASPNETMVCApplication.Repositories;
using ASPNETMVCApplication.ActionServiceReference;
using ASPNETMVCApplication.Areas.Shop.Models;
using ASPNETMVCApplication.Code.HtmlHelpers;
using ASPNETMVCApplication.Controllers;
using ASPNETWebApplication;
using ASPNETMVCApplication.Areas.Supp.ViewModels;

namespace ASPNETMVCApplication.Areas.Shop.Controllers
{
    /// <summary>
    /// Controller class for the Shopping area.
    /// </summary>
    public class ShopController : BaseController
    {
        private ICategoryRepository _categoryRepository;
        private IProductRepository _productRepository;
        private ICartRepository _cartRepository;
        private IOrderRepository _orderRepository;
        /// <summary>
        /// Default Constructor for ShopController.
        /// </summary>
        public ShopController()
            : this(new CategoryRepository(),
                   new ProductRepository(),
                   new CartRepository(),
                    new OrderRepository())
        {
        }

        /// <summary>
        /// Overloaded 'injectable' Constructor for ShopController.
        ///
        /// Pattern: Constructor Dependency Injection (DI).
        /// </summary>
        /// <param name="categoryRepository"></param>
        /// <param name="productRepository"></param>
        /// <param name="cartRepository"></param>
        public ShopController(ICategoryRepository categoryRepository,
            IProductRepository productRepository,
            ICartRepository cartRepository,
            IOrderRepository orderRepository)
        {
            _categoryRepository = categoryRepository;
            _productRepository = productRepository;
            _cartRepository = cartRepository;
            _orderRepository = orderRepository;
        }

        /// <summary>
        /// Action method. 
        /// Prepares shopping home page view (Index) 
        /// </summary>
        /// <returns></returns>
        [Menu(MenuItem.Shopping)]
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        ///  Action method. 
        ///  Gets category and product data.
        ///  Product data is filtered by category and sorted.
        /// </summary>
        /// <param name="categoryId">Category for which to filter products. Default is ProductId 1.</param>
        /// <param name="sort">Sort of product list. Default is product Id.</param>
        /// <param name="order">Sord order of product list. Default = 'asc'.</param>
        /// <returns></returns>
        [Menu(MenuItem.Products)]
        public ActionResult Products(int categoryId = 1, string sort = "productid", string order = "asc")
        {
            // Selectlist of categories dropdown
            ViewData["Categories"] = new SelectList(_categoryRepository.GetList(), "CategoryId", "Name", categoryId);

            var criterion = new Criterion(sort, order, "CategoryId", Operator.Equals, categoryId);
            return View(new SortedList<ProductModel>(_productRepository.GetList(criterion).ToModel(), sort, order));
        }

           
        //[Menu(MenuItem.Search)]
        //public ActionResult Search(string productName = "", string ranges = "0", string sort = "productid", string order = "asc")
        //{
        //    ViewData["ProductName"] = productName;
        //    ViewData["Ranges"] = new SelectList(PriceRange.List, "RangeId", "RangeText", ranges); 

        //    var productModels = new List<ProductModel>();
        //    if (Request.HttpMethod == "POST")
        //    {
        //        var model = _productRepository.Search(productName, int.Parse(ranges), sort, order).ToModel();
        //        return View(new SortedList<ProductModel>(model, sort, order));
        //    }

        //    return View(new SortedList<ProductModel>(new List<ProductModel>(), sort, order));
        //}

        /// <summary>
        /// Action method. HTTP GET only.
        /// Gets shopping cart data and shipping options.
        /// </summary>
        /// <returns></returns>
        [HttpGet, Menu(MenuItem.Cart)]
        public ActionResult Cart()
        {
            var cart = _cartRepository.GetCart();

            // Populate and select shipping dropdown
            ViewData["Shipping"] = new SelectList(ShippingMethod.List, "ShippingId", "ShippingName", GetShippingId(cart.ShippingMethod));

            return View(cart.ToModel());
        }

        /// <summary>
        /// Action method. HTTP POST only.
        /// Deletes a shopping cart item.
        /// </summary>
        /// <param name="delete">Product id of item do delete.</param>
        /// <returns></returns>
        [HttpPost, Menu(MenuItem.Cart)]
        public ActionResult Cart(string delete = null)
        {
            if (!string.IsNullOrEmpty(delete))
            {
                int productId = int.Parse(delete);
                _cartRepository.Delete(productId);
            }

            return RedirectToAction("Cart");
        }

        /// <summary>
        /// Action method.
        /// Checkout shopping cart (not implemented).
        /// </summary>
        /// <returns></returns>
        [Menu(MenuItem.Cart)]
        public ActionResult Checkout()
        {
            return View();
        }

        /// <summary>
        /// Action method. HTTP POST only.
        /// Recalculate shopping cart. Evaluate each item's quantity.
        /// </summary>
        /// <param name="formCollection"></param>
        /// <returns></returns>
        [HttpPost, Menu(MenuItem.Cart)]
        public ActionResult Recalculate(FormCollection formCollection)
        {
            foreach (var key in formCollection.AllKeys)
            {
                if (key.StartsWith("prodid-"))
                {
                    // Extract productId for cart line item.
                    int productId = int.Parse(key.Substring(7));

                    int quantity;
                    if (!int.TryParse(formCollection[key], out quantity))
                        quantity = 0;

                    if (quantity > 0 && quantity < 100)
                        _cartRepository.Update(new ShoppingCartItem { Id = productId, Quantity = quantity }); 
                    else
                        _cartRepository.Delete(productId);
                }
            }

            return RedirectToAction("Cart");
        }

        /// <summary>
        /// Action method. HTTP POST only.
        /// Updates shipping method.  Cart page will display updated total, subtotals, etc.
        /// </summary>
        /// <param name="shippingId"></param>
        /// <returns></returns>
        [HttpPost, Menu(MenuItem.Cart)]
        public ActionResult Shipping(string shippingId)
        {
            if (!string.IsNullOrEmpty(shippingId))
            {
                string method = GetShippingMethod(int.Parse(shippingId));
                _cartRepository.UpdateShippingMethod(method);
            }

            return RedirectToAction("Cart");
        }

        // Helper method. Returns shipping id based on shipping method provided.
        private int GetShippingId(string shippingMethod)
        {
            return ShippingMethod.List.Single(m => m.ShippingName == shippingMethod).ShippingId;
        }

        // Helper method. Returns shipping method given a shipping identifier.
        private string GetShippingMethod(int shippingId)
        {
            return ShippingMethod.List.Single(m => m.ShippingId == shippingId).ShippingName;
        }


        // TAIPM : 02/01/2011
        /// <summary>
        /// Action method. HTTP POST only.
        /// Saves changed (new or updated) product record.
        /// </summary>
        /// <param name="model">The product model with changed data.</param>
        /// <returns></returns>
        [HttpPost]        
        public ActionResult Product(ProductModel model)
        {
            int selectedStatus = int.Parse(Request["statusId"]);

            model.StatusId = selectedStatus;

            if (ModelState.IsValid)
            {
                var product = model.FromModel();
                if (product.ProductId > 0)
                    _productRepository.Update(product);
                else
                    _productRepository.Insert(product);

                return RedirectToAction("Products");
            }

            SetProductViewData(model.ProductId);

            // Show with errors
            return View(model);
        }


        // TAIPM : 09/01/2011
        /// <summary>
        /// Action method. HTTP POST only.
        /// Saves changed (new or updated) product record.
        /// </summary>
        /// <param name="model">The product model with changed data.</param>
        /// <returns></returns>
        [HttpPost]        
        public ActionResult Book(int productId)
        {
            int selectedStatus = int.Parse(Request["statusId"]);
            
            if (ModelState.IsValid)
            {
                _productRepository.Book(productId, selectedStatus);                
                
                return RedirectToAction("Products");
            }

            var model = productId == 0 ? new ProductModel() : _productRepository.Get(productId).ToModel();
            SetProductViewData(model.ProductId);

            // Show with errors
            return View(model);
        }

        [HttpGet]
        public ActionResult Product(int productId)
        {
            SetProductViewData(productId);

            var model = productId == 0 ? new ProductModel() : _productRepository.Get(productId).ToModel();

            if (productId == 0)
            {
                return View("Create", model);
            }
            else
            {
                return View(model);
            }
        }

        //vietnh
        [HttpGet]
        public ActionResult Product(int productId, int categoryId)
        {
            SetProductViewData(productId);

            var model = productId == 0 ? new ProductModel() : _productRepository.Get(productId,categoryId).ToModel();

            if (productId == 0)
            {
                return View("Create", model);
            }
            else
            {
                return View(model);
            }
        }

        // TAIPM : 02/01/2010
        // private Helper
        private void SetProductViewData(int? productId = 0)
        {
            ViewData["BreadCrumbs"] = new List<BreadCrumb> { 
                new BreadCrumb { Url = UrlMaker.ToDefault(), Title = "home" }, 
                new BreadCrumb { Url = UrlMaker.ToAdmin(), Title = "administration" }, 
                new BreadCrumb { Url = UrlMaker.ToProducts(), Title = "products" },
                new BreadCrumb { Url = UrlMaker.ToProduct(productId), Title = "product" },                
                new BreadCrumb { Title = "product details" } };

            ViewData["ProductImage"] = imageService + "GetProductImageLarge/" + productId;            
        }

        public ActionResult CheckOutOrder()
        {
            List<CartViewModels> listCartItem = (List<CartViewModels>)Session["CartView"];
            
            //if (listCartItem != null && Session["CustomerId"]!=null)
            //{
               
            //}
            int customerId = 1; //(int)Session["CustomerId"];

            

            foreach (CartViewModels cartItem in listCartItem)
            {
                for (int i = 0; i < cartItem._ghemua.Count; i++)
                {
                    cartItem._ghemua[i].Status = 1;
                    cartItem._ghemua[i].Version = "0";
                }
                    OrderTicket(cartItem._supplier.SupplierId, customerId, "beckham", cartItem._ghemua);
            }
            return View();
        }

        private void OrderTicket(int supplierID,int customerID, string customerName, List<Product> productList)
        {
            List<OrderDetail> listDetail = new List<OrderDetail>();
            List<int> ChairList = new List<int>();
            List<string> ChairNameList = new List<string>();
            int CategoryId = 0;
            //cập nhật trạng thái vé
            if (productList.Count > 0)
            {
                

                for (int i = 0; i < productList.Count; i++)
                {
                    _productRepository.Update(productList[i]);
                    var detail = new OrderDetail();
                    detail.CategoryId = productList[i].CategoryId;
                    detail.Discount = 0;
                    detail.ProductId = productList[i].ProductId;
                    detail.ProductName = "";
                    detail.Quantity = 1;
                    detail.Status = 0;
                    detail.Version = "0";
                    listDetail.Add(detail);
                    ChairList.Add(productList[i].ProductId);
                    ChairNameList.Add(productList[i].ChairNumber.ToString());
                    CategoryId = productList[i].CategoryId; ;
                }
            }

            Order orderHeader = new Order();
            orderHeader.CustomerId = customerID;
            orderHeader.SupplierId = supplierID;
            orderHeader.OrderDate = DateTime.Now;
            orderHeader.RequiredDate = DateTime.Now;
            orderHeader.Freight = 0;
            orderHeader.Status = 0;
            orderHeader.OrderDetails = null;

            _orderRepository.InsertOrder(orderHeader, ChairList,ChairNameList, CategoryId);
            Session.Remove("CartView");
        }
    }
}


